#include <QtSql>

#include <QApplication>
#include <QDebug>
#include <QDir>
#include <QMessageBox>

#include "maindialog.h"
#include "service.h"
#include "settings.h"


QString logFileName;
void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    Q_UNUSED(context);

    QString dt = QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss");
    QString txt = QString("[%1] ").arg(dt);

    switch (type)
    {
    case QtDebugMsg:
        txt += QString("{Debug}\t\t%1").arg(msg);
        break;
    case QtWarningMsg:
        txt += QString("{Warning}\t%1").arg(msg);
        break;
    case QtCriticalMsg:
        txt += QString("{Critical}\t%1").arg(msg);
        break;
    case QtFatalMsg:
        txt += QString("{Fatal}\t\t%1").arg(msg);
        abort();
        break;
    }

    QFile outFile(logFileName);
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);

    QTextStream textStream(&outFile);
    textStream << txt << endl;
}


int main(int argc, char *argv[])
{
    int result;

    QApplication a(argc, argv);

    QApplication::setOrganizationName("Majister");
    QApplication::setApplicationName("jPos");
    /*
        QDir dir(":/qss/qss");
        QFileInfoList dirList = dir.entryInfoList();
        for (int i = 0; i < dirList.size(); ++i) {
              qDebug()<<dirList.at(i).fileName();
         }
*/
/*
    QFile file1("d:\\stylesheet.qss");
    file1.open(QFile::WriteOnly);
    file1.write(qApp->styleSheet().toLatin1());
    file1.close();
*/
    QFile file(":/qss/qss/black-n-orange.qss");
    file.open(QFile::ReadOnly);
    QString styleSheet = QString::fromLatin1(file.readAll());
    qApp->setStyleSheet(styleSheet);

    QString mainBase  = "";//"db.sqlite3";
    logFileName.clear();

    QString dbDriver   = "QIBASE";
    QString dbUser      = "SYSDBA";
    QString dbPass       = "masterkey";
    QString dbOptions = "CHARSET=WIN1251";

    int loglevel = 1;
    bool newlog=false;


    QStringList args = QCoreApplication::arguments();
    for (int i=1;i<args.count();++i){
        QString value = args.at(i);

        if (value == "--logfile" && i<args.count())
        {
            logFileName = args.at(++i);
            continue;
        }

        if (value == "--loglevel" && i<args.count())
        {
            loglevel = args.at(++i).toInt();
            continue;
        }

        if (value == "--newlog" && i<args.count())
        {
            newlog=true;
            continue;
        }

        if (value == "--driver" && i<args.count())
        {
            dbDriver = args.at(++i);
            continue;
        }
        if (value == "--user" && i<args.count())
        {
            dbUser = args.at(++i);
            continue;
        }
        if (value == "--password" && i<args.count())
        {
             dbPass = args.at(++i);
            continue;
        }

       if (!value.startsWith("-")){
                mainBase = value;
        }
    }

    if(newlog){
        QFile::remove(logFileName);
    }

    if(!logFileName.isEmpty())
        qInstallMessageHandler(customMessageHandler);


    if(loglevel>0){
      qDebug()<<(loglevel>1?posInFile:"")<<"Уровень лога: "<<loglevel;

      qDebug()<<(loglevel>1?posInFile:"")<<"База данных: "<<mainBase;
      qDebug()<<(loglevel>1?posInFile:"")<<"Драйвер: "<<dbDriver;
      qDebug()<<(loglevel>1?posInFile:"")<<"Пользователь: "<<dbUser;
      qDebug()<<(loglevel>1?posInFile:"")<<"Пароль: "<<dbPass;
      qDebug()<<(loglevel>1?posInFile:"")<<"Настройки: "<<dbOptions;
    }

    Settings::checkDefaults();

    Settings::getVariables()->insert("loglevel", loglevel);

    /*
    if(mainBase.isEmpty())
    {
        qCritical()<<posInFile<<endl<<"Database is not specified";
        return 1;
    }
*/

    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);

    db.setDatabaseName(mainBase);
    db.setUserName(dbUser);
    db.setPassword(dbPass);
    db.setConnectOptions(dbOptions);

    if (!db.open())
    {
        qCritical()<<(loglevel>1?posInFile:"")<<endl<<"Ошибка подключения :"<<endl<<db.lastError().text();

        QMessageBox message;
        message.setText("Ошибка подключения к базе данных\nТекст: \n"+db.lastError().text());
        message.exec();

        return 2;
    }

    if(loglevel > 0)
     qDebug()<<(loglevel>1?posInFile:"")<<"Запуск ";

    MainDialog w;
    w.showFullScreen();
    result = a.exec();

    db.close();

    if(loglevel > 0)
     qDebug()<<(loglevel>1?posInFile:"")<<"Выход,  код ошибки: "<<result;

    return result;
}
